$(function() {
    var conn = null;
    var point = 0; // 0登录, 1大厅, 2房间
    var room = -1;
    var role = 0;
    var uname;
    var uid;
    var room_state;
    var judge_uid;
    var wcard_need = 0; // 本回合需要白卡张数
    var wcard_send_lst = []; // 需要白卡多于一张的时候，存白卡的列表

    function log(msg) {
        //var control = $('#log');
        //control.html(control.html() + msg + '<br/>');
        //control.scrollTop(control.scrollTop() + 1000);
        console.log(msg);
    }

    String.prototype.trim = function() {
          return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }

    function msg_print(msg) {
        var control;
        if (point == 1) control = $('#messageInfoList');
        else control = $("#chatInfo");
        control.html(control.html() + msg + '<br/>');
        control.scrollTop(control.scrollTop() + 1000);
    }

    function room_add(info) {
        var rid  = info[0];
        var np  = info[1];
        var no  = info[2];
        $("#rooms").append("<div><span>"+rid+"<br></span><span>默认房间<br></span><span>玩家："+np+" 观众："+no+"<br></span><span>等待中</span></div>");
        $("#rooms > div:last-child").click(function() {
            conn.send(JSON.stringify([
                ['room_join', rid],
            ]));
        });
    }

    function connect() {
        disconnect();

        var transports = [
            "websocket", "xhr-streaming", "iframe-eventsource", "iframe-htmlfile", "xhr-polling", "iframe-xhr-polling", "jsonp-polling"
        ];

        conn = new SockJS('http://' + window.location.host + '/ws/api', transports);

        log('Connecting...');

        conn.onopen = function() {
            log('Connected.');
            conn.send(JSON.stringify([
                ['set_uname',uname],
                ['room_join', 0],
                ['room_list'],
            ]));
            $('#login_page').hide();
            $('#lobby_page').show();
            point = 1;
        };

        conn.onmessage = function(e) {
            var data = JSON.parse(e.data);
            for (var i in data) {
                var info = data[i];
                if (info[0] == 'say') {
                    msg_print(info[1]);
                } else if (info[0] == 'user_info') {
                    uid = info[1];
                } else if (info[0] == 'room_add') {
                    room_add(info[1]);
                } else if (info[0] == 'room_info') {
                    room = info[1];

                    if (room == 0) {
                        // 如果自己加入了大厅
                        $('#lobby_page').show();
                        $('#game_page').hide();
                        $("#playerInfoList").html("");
                        for (j in info[3]) {
                            $("#playerInfoList").append("<span alt='" + info[3][j][0] + "'>" + info[3][j][1]+ "</span>");
                        }
                        point = 1;
                    } else {
                        $('#lobby_page').hide();
                        $('#game_page').show();
                        point = 2;
                        // 清空数据
                        $("#mostRight #playerList").html("");
                        $("#mostRight #spectatorList").html("");
                        // 添加玩家
                        for (j in info[2]) {
                            var _info = info[2][j];
                            $("#mostRight #playerList").append('<div alt="'+_info[0]+'" class="playerSlotContainer"><div class="playerPoint">0</div><div class="playerSlot">'+_info[1]+'</div></div>');
                        }
                        // 添加观察者
                        for (j in info[3]) {
                            var _info = info[3][j];
                            $("#mostRight #spectatorList").append('<div alt="'+ _info[0]+'" class="spectatorSlot">'+_info[1]+'</div>');
                        }
                        // 设置裁判
                        if (info[4] != -1) {
                            judge_uid = $($("#mostRight #playerList > div")[info[4]]).attr('alt');
                            $($("#mostRight #playerList > div")[info[4]]).append("<span>裁判</span>");
                        }

                        // 标记已经出牌的玩家
                        for (var i in info[5]) {
                            var _uid = info[5][i];
                            var lst = $("#mostRight #playerList > div");
                            for (var i=0;i<lst.length;i++) {
                                if ($(lst[i]).attr('alt') == _uid)
                                    $(lst[i]).addClass("sent");
                            }
                        }
                    }
                } else if (info[0] == 'room_leave') {
                    // 在大厅中
                    if (room == 0) {
                        var items = $("#playerInfoList > span");
                        for (var j=0;j<items.size();j++) {
                            if ($(items[j]).attr('alt') == info[1]) {
                                items[j].remove();
                                break;
                            }
                        }
                    } else {
                        var lst = $("#mostRight #playerList > div");
                        for (var i=0;i<lst.length;i++) {
                            if ($(lst[i]).attr("alt") == info[1]) {
                                $(lst[i]).remove();
                                break;
                            }
                        }

                        lst = $("#mostRight #spectatorList > div");
                        for (var i=0;i<lst.length;i++) {
                            if ($(lst[i]).attr("alt") == info[1]) {
                                $(lst[i]).remove();
                                break;
                            }
                        }
                    }
                } else if (info[0] == 'room_list') {
                    // 获取了房间列表
                    $("#rooms").html("");
                    for (var j in info[1]) {
                        room_add(info[1][j]);
                    }
                } else if (info[0] == 'room_state') {
                    var s = info[1];
                    // 缺人，回复至初始状态
                    if (s == 1) {
                        // 清空手牌
                        $("#white_cards").html("");
                        // 隐藏黑板
                        $("#blackCardTop").hide();
                        $('#blackCardContent').hide();
                    // 人齐，游戏可以开始
                    } else if (s == 2) {
                        $("#blackCardTop").show();
                    // 游戏已经开始
                    } else if (s == 3) {
                        $("#blackCardTop").hide();
                    }
                    room_state = s;
                } else if (info[0] == 'wcard_get') {
                    $("#white_cards").append('<div class="handCardSlot">'+ info[1][2] +'</div>');
                    $("#white_cards > div:last-child").click(function() {
                        if (room_state == 3 && judge_uid != uid) {
                            var cid = $("#white_cards > div").index(this);
                            wcard_send_lst.push(cid);
                            if (wcard_send_lst.length == wcard_need) {
                                conn.send(JSON.stringify([
                                    ['wcard_send', wcard_send_lst],
                                ]));
                                wcard_send_lst = []
                            } else {
                                $(this).addClass('sent');
                            }
                        }
                    });
                } else if (info[0] == 'wcard_sent') {
                    var uindex = info[1];
                    var utip = $($("#mostRight #playerList > div")[uindex]);
                    utip.addClass("sent");
                    if (utip.attr('alt') == uid) {
                        for (var i in info[2]) {
                            $("#white_cards > div")[i].remove();
                        }
                    }
                } else if (info[0] == 'jcard_add') {
                    $("#jcards").append('<div class="cardSlot">'+info[1]+'</div>');
                    $("#jcards > div:last-child").click(function() {
                        var cid = $("#jcards > div").index(this);
                        conn.send(JSON.stringify([
                            ['wcard_choose', cid],
                        ]));
                    });
                // 这一条暂时放弃不用
                } else if (info[0] == 'bcard_get') {
                    $('#blackCardContent').show();
                    $('#blackCardContent').html(info[1][2]);
                // 这一条代替上一条
                } else if (info[0] == 'bcard_set') {
                    $('#blackCardContent').show();
                    $('#blackCardContent').html(info[1]);
                    wcard_need = info[2];
                } else if (info[0] == 'judge_set') {
                    $($("#mostRight #playerList > div > span")).remove();
                    $($("#mostRight #playerList > div")[info[1]]).append("<span>裁判</span>");
                    judge_uid = $($("#mostRight #playerList > div")[info[1]]).attr('alt');

                    // 如果裁判是自己，并且本轮2张白卡
                    if (judge_uid == uid) {
                        wcard_send_lst = [];
                        $("#white_cards > div").removeClass('sent');
                    }
                } else if (info[0] == 'wcard_choose') {
                    $($("#jcards > div")[info[1]]).append('-> 选择');
                    $($("#mostRight #playerList > div")[info[2]]).append('<span>得分</span>');
                    // 进入下一轮
                    setTimeout(function() {
                        $("#jcards > div").remove();
                        $("#white_cards > div").removeClass('sent');
                        $("#mostRight #playerList > div").removeClass('sent');
                        //$('#blackCardContent').html("");
                    }, 1000);
                } else if (info[0] == 'jcard_remove') {
                    $("#jcards > div")[info[1]].remove();
                }
            }
        };

        conn.onclose = function() {
            log('Disconnected.');
            conn = null;
        };
    };

    function disconnect() {
        if (conn != null) {
            log('Disconnecting...');

            conn.close();
            conn = null;
        }
    };


    // 登录
    $("#login_btn").click(function() {
        uname = $("#login_text")[0].value.trim();
        if (uname == "") {
            alert("用户名不能为空!");
            return;
        } else if (uname.length > 20) {
            alert("用户名太长!");
            return;
        }
        if (conn == null) {
            $("#login_btn").attr('value', "连接中...");
            connect();
        }
        //else conn.send(JSON.stringify({'set_uname':uname}));
    });

    // 添加房间
    $("#btn_room_add").click(function() {
        conn.send(JSON.stringify([
            ['room_add'],
        ]));
    });


    // 发言
    $("#inputMessageText").keydown(function(e){
        if (e.keyCode == 13) {
            conn.send(JSON.stringify([
                ['say', $("#inputMessageText")[0].value],
            ]));
            $("#inputMessageText")[0].value = '';
        }
    });

    $("#chatMessage").keydown(function(e){
        if (e.keyCode == 13) {
            conn.send(JSON.stringify([
                ['say', $("#chatMessage")[0].value],
            ]));
            $("#chatMessage")[0].value = '';
        }
    });

    // 离开房间
    $("#leaveRoomButton").click(function() {
        conn.send(JSON.stringify([
            ['room_join', 0],
            ['room_list'],
        ]));

    });

    // 变更身份
    $("#spectateButton").click(function() {
        $("#white_cards").html("");
        conn.send(JSON.stringify([
            ['room_player', role==1?0:1],
        ]));
        role = role==1?0:1;
    });

    // 变更身份
    $("#blackCardTop").click(function() {
    });

    // 开始游戏
    $("#gameStartButton").click(function() {
        conn.send(JSON.stringify([
            ['game_start'],
        ]));
    });

});

